﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using arb.Generic.SharedLibrary.exceptionHandling;
using System.Diagnostics;

namespace TomShirley.WebParts.AccessChecker
{
    /// <summary>
    /// Abstract class for creating a WebPart with an EditorPart
    /// </summary>
    /// <typeparam name="T">The EditorClass to use</typeparam>
    public abstract class BaseWebPart<T> : System.Web.UI.WebControls.WebParts.WebPart, IWebEditable where T : BaseEditorPart, new()
    {

        /// <summary>
        /// Renders an error to the writer
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="control"></param>
        protected void RenderError(HtmlTextWriter writer, Control control)
        {
            Table table = new Table();
            TableRow row = new TableRow();
            table.Rows.Add(row);
            row.Cells.Add(new TableCell());
            row.Cells[0].Controls.Add(control);
            table.RenderControl(writer);
        }

        /// <summary>
        /// Displays a generic error to the user.
        /// </summary>
        /// <param name="errorMessage">The error message.</param>
        /// <param name="writer">The writer.</param>
        protected static void DisplayErrorToUser(string errorMessage, System.Web.UI.HtmlTextWriter writer)
        {
            HtmlGenericControl errorControl = new HtmlGenericControl("DIV");
            errorControl.Attributes.Add("style", "padding: 20px; margin: 20px; border-style: groove; background-color: #FFFFFF;");
            errorControl.InnerHtml = "<IMG src=\"/_layouts/images/error16by16.gif\" border=\"0\"/>" + errorMessage;
            errorControl.RenderControl(writer);
        }

        /// <summary>
        /// will return ex.ToString() or ex.Message depending on the compilation settings
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        protected static string GetErrorMessage(Exception ex)
        {
            if (ex != null)
            {
                #if DEBUG
                    return ex.ToString();
                #else
                    return ex.Message;
                #endif
            }
            return string.Empty;
        }

        /// <summary>
        /// Creates a control containing an error message
        /// </summary>
        /// <param name="message"></param>
        /// <param name="useToolpane">Set to true if a link to the toolpane should be provided</param>
        /// <returns></returns>
        protected Label CreateErrorControl(string message, bool useToolpane)
        {
            Label label = new Label();
            LiteralControl content = new LiteralControl();
            content.Text = message;
            label.Controls.Add(content);
            HyperLink hl = new HyperLink();
            hl.NavigateUrl = string.Format("javascript:MSOTlPn_ShowToolPane2Wrapper('Edit','129','{0}');", this.ID);
            hl.ID = string.Format("MsoFrameworkToolpartDefmsg_{0}", this.ID);
            hl.Text = "Click here to open the Tool Pane...";
            label.Controls.Add(new LiteralControl("<br/>"));
            label.Controls.Add(hl);
            return label;
        }

        #region IWebEditable Members

        EditorPartCollection IWebEditable.CreateEditorParts()
        {
            List<EditorPart> editors = new List<EditorPart>();
            T editor = new T();
            editor.ID = this.ID + editor.EditorName;
            editors.Add(editor);
            return new EditorPartCollection(editors);
        }

        object IWebEditable.WebBrowsableObject
        {
            get { return this; }
        }

        #endregion

        protected void LogError(string message, string EventSourceName, string logPath)
        {
            GenericExceptionHandler.LogPath = logPath;
            GenericExceptionHandler.StartLogging();
            GenericExceptionHandler.TraceLevel = TraceLevel.Verbose;
            GenericExceptionHandler.EventSourceName = EventSourceName;
            GenericExceptionHandler.WriteLine(TraceLevel.Error, message);
            GenericExceptionHandler.StopLogging();
        }

        protected string GetClassResourceFilePath(string resourcePath)
        {
            // Returns the physical path of the class resource folder
            int iPos = 0;
            string sPrecedingPath = "";
            string sResourcePath = resourcePath;

            // Get the position of the wpresources text
            iPos = sResourcePath.ToLower().IndexOf("wpresources");

            // Get the part of the string preceeding the wpresources text
            sPrecedingPath = sResourcePath.Substring(1, iPos);

            // Get the position of the preceding slash to get the start
            // of the string to return

            // This allows both the GAC and the /bin wpresource
            // locations - ie /_wpresources or /wpresources

            iPos = sPrecedingPath.LastIndexOf("/") + 1;

            if (iPos > 1)
            {
                sResourcePath =
                    sResourcePath.Substring(iPos,
                    sResourcePath.Length - iPos);
            }

            return this.Context.Server.MapPath(sResourcePath);
        }
    }
}
